<?php

namespace App\Http\Controllers\Export;

use App\Http\Controllers\Controller;
use App\Models\Survey;
use App\Models\SurveyAnswer;
use App\Models\SurveyProblem;
use App\Models\SurveyReply;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * excel导出导入功能
 */
class SurveyExport extends Controller
{

    public $model = null;
    public $replyModel = null;


    public function __construct()
    {
        parent::__construct();

        $this->model = new Survey();
        $this->replyModel = new SurveyReply();
    }

    /**
     * 问卷调查答案导出 (老版，答案分别显示)
     * @param id string 问卷调查id
     * @param keywords 检索内容
     */
    public function index()
    {
        $id = $this->request->id;
        if (empty($id)) {
            return $this->returnApi(201, "问卷id不能为空");
        }

        $keywords = $this->request->keywords;

        // 获取问卷调查是否存在
        $res = $this->model->select('id', 'survey_name')
            ->where("is_del", 1)
            ->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        // 获取所有问题
        $data = $this->replyModel->getReplyList($id, $keywords);
        //设置表头
        $row = [[
            "id" => '序号',
            "nickname" => '用户昵称',
            "problem" => '问题',
            "type" => '类型',
            "content" => '答案',
            "create_time" => '回复时间',
        ]];

        $title = '问卷调查用户回复数据导出-' . date('YmdHis');
        //执行导出
        $data = $this->setData($data); //要导入的数据
        return $this->exportData($data, $title, $row);
    }

    /**
     * 问卷调查答案导出 (2.0版，按用户答案合并显示)
     * @param id string 问卷调查id
     * @param keywords 检索内容
     */
    public function indexMerge()
    {
        $id = $this->request->id;
        if (empty($id)) {
            return $this->returnApi(201, "问卷id不能为空");
        }

        $keywords = $this->request->keywords;

        // 获取问卷调查是否存在
        $res = $this->model->select('id', 'survey_name')
            ->where("is_del", 1)
            ->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        // 获取问卷调查是否存在
        $problem = SurveyProblem::select('id', 'problem', 'type')
            ->where("sur_id", $this->request->id)
            ->orderBy('id')
            ->get()
            ->toArray();

        if (empty($problem)) {
            return $this->returnApi(203, "暂无数据");
        }

        // 获取所有问题
        $data = $this->replyModel->getReplyList($id, $keywords);
        //设置表头
        $temp_row = [
            "id" => '序号',
            "nickname" => '用户昵称',
        ];

        foreach ($problem as $key => $val) {
            $type = $val['type'] == 1 ? '多选题' : ($val['type'] == 2 ? '单选题' : '填空题');
            $temp_row['problem_' . $val['id']] = '（' . ($type) . '）' . $val['problem'];
        }
        $temp_row['create_time'] = '回复时间';
        $row[] = $temp_row;
        $title = '问卷调查用户回复数据导出-' . date('YmdHis');
        //执行导出
        $data = $this->setData2($data, $problem); //要导入的数据
        return $this->exportData($data, $title, $row);
    }


    /**
     * 导出数据
     *
     * @param [type] $data
     * @return void
     */
    public function exportData($data, $title, $row)
    {
        $header = $row; //导出表头
        $excel = new Export($data, $header, $title);
        $excel->setColumnWidth(['A' => 10, 'B' => 20, 'C' => 20, 'D' => 20, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 20, 'I' => 20, 'J' => 20, 'K' => 20, 'L' => 20, 'M' => 20, 'N' => 20, 'O' => 20, 'P' => 20, 'Q' => 20, 'R' => 20, 'S' => 20, 'T' => 20, 'U' => 20, 'V' => 20, 'W' => 20, 'X' => 20, 'Y' => 20, 'Z' => 20]);
        $excel->setRowHeight([1 => 30]);
        // $excel->setFreezePane('A2');
        // $excel->setFont(['A1:Z1265' => '宋体']);
        // $excel->setFontSize(['A1:I1' => 14,'A2:Z1265' => 10]);
        // $excel->setBold(['A1:Z2' => true]);
        // $excel->setBackground(['A1:A1' => '808080','C1:C1' => '708080']);
        // $excel->setMergeCells(['A1:I1']);
        // $excel->setBorders(['A2:D5' => '#000000']);
        return Excel::download($excel, $title . '.xlsx');
    }


    /**
     * 处理 终端书籍列表 数据
     */
    public function setData($data)
    {
        $excel_data = [];
        /*设置excel内容*/
        foreach ($data as $key => $val) {
            $excel_data[$key]['id'] = $key + 1;
            $excel_data[$key]['nickname'] = $val['nickname'];
            $excel_data[$key]['problem'] = $val['problem'];
            $excel_data[$key]['type'] = $val['type'];
            $excel_data[$key]['content'] = $val['content'];
            $excel_data[$key]['create_time'] = $val['create_time'];
        }
        return $excel_data;
    }


    /**
     * 处理 终端书籍列表 数据
     */
    public function setData2($data, $problem)
    {
        $excel_data = [];
        /*设置excel内容*/
        $user_id_arr = [];
        foreach ($data as $key => $val) {
            if (!in_array($val['user_id'], $user_id_arr)) {
                $val['user_id'];
            }
            $excel_data[$val['user_id']]['id'] = count($user_id_arr) + 1;
            $excel_data[$val['user_id']]['nickname'] = $val['nickname'];
            foreach ($problem as $k => $v) {
                if ($val['pro_id'] == $v['id']) {
                    $excel_data[$val['user_id']]['problem_' . $v['id']] = $val['content'];
                }
            }
            if (count($problem) + 2 == count($excel_data[$val['user_id']])) {
                $excel_data[$val['user_id']]['create_time'] = $val['create_time'];
            }
        }
        sort($excel_data);
        return $excel_data;
    }
}
